package com.mstanford.movie.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mstanford.movie.dao.MovieDao;
import com.mstanford.movie.utils.DataUtil;
import com.mstanford.movie.utils.SendHtmlEmail;

public class BackTicketServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		Object obj = request.getSession().getAttribute("member");
		if(DataUtil.isEmpty(obj)) {
			response.sendRedirect("login.jsp");
			return;
		}
		
		Map<String, String> member = (Map<String, String>)obj;
		String memberId = member.get("memberId");
		String memberEmail = member.get("memberEmail");
		String memberName = member.get("memberName");
		String memberGender = member.get("memberGender");
		memberGender = "1".equals(memberGender) ? "男士" : "女士";
		
		String ticketId = request.getParameter("ticketId");
		String ticketCode = request.getParameter("ticketCode");
		String movieName = request.getParameter("movieName");
		
		String playTime1 = request.getParameter("playTime1");
		Date date = DataUtil.string2Date(playTime1, "yyyy-MM-dd HH:mm");
		playTime1 = DataUtil.date2String(date, "yyyy年MM月dd日 E HH时mm分");
		
		String ticketSeat = request.getParameter("ticketSeat");
		String ticketPrice = request.getParameter("ticketPrice");
		String ticketFlag = request.getParameter("ticketFlag");

		MovieDao dao = new MovieDao();
		dao.updateTicketFlagByTicketId(ticketId, ticketFlag);
		dao.updateAddMemberMoneyByMemberId(memberId, ticketPrice);
		
		StringBuffer msg = new StringBuffer();
		msg.append("尊敬的&nbsp;&nbsp;").append(memberName).append(memberGender)
		   .append("&nbsp;&nbsp;您好：退票成功！以下是退票信息：<br/>")
		   .append("订单号：").append(ticketCode).append("&nbsp;电影：").append(movieName)
		   .append("&nbsp;场次时间：").append(playTime1).append(ticketSeat).append("座");
		

		SendHtmlEmail.sendEmail(memberEmail, msg.toString());
		
		String json = "{\"result\":true}";
		
		// 返回Json格式信息
		response.setContentType("application/json; charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		out.print(json);
		out.flush();
		out.close();
	}
}